module detector (
    input wire clock,
    input wire reset,
    input wire data,
    output wire div_clk
);
    reg div_clk1;
    reg [15:0] counter, diver1;
    reg [9:0] rs1, rs2, rsf;
    reg [1:0] state, div_state1;

    assign div_clk = div_clk1;


    always @(posedge clock or negedge reset) begin
        if (~reset) begin
            counter <= 0;
        end
        else begin
            counter <= counter + 1;
        end
    end

    always @(posedge data or negedge reset) begin
        if (~reset) begin
            state <= 2'b00;
            rs1 <= 0;
            rs2 <= 0;
        end
        else begin
            //if (state == 2'b00 && clk_locked) begin
            if (state == 2'b00) begin
                rs1 <= counter;
                state <= 2'b01;
            end
            else if (state == 2'b01) begin
                rs2 <= (counter - rs1) >> 1;
                state <= 2'b10;
            end
        end
    end


    always @(posedge clock or negedge reset) begin
        if (~reset) begin
            diver1 <= 0;
            div_clk1 <= 0;
            rsf <= 0;
            div_state1 <= 2'b00;
        end
        else begin
            if (div_state1 == 2'b00 && state == 2'b10 && data == 0) begin
                div_state1 <= 2'b01;
                diver1 <= 1;
            end
            else if (div_state1 == 2'b01) begin
//                diver1 <= 3;
                if (diver1 == rs2) begin
                    div_clk1 <= ~div_clk1;
                    diver1 <= 1;
                    div_state1 <= 2'b10;
                    if(rs2 % 2 == 1) begin
                        rsf <= 1;
                    end
                end
                else begin
                    diver1 <= diver1 + 1;
                end
            end
            else if (div_state1 == 2'b10) begin
                if(div_clk1 == 1) begin
                    if (diver1 == (rs2>>1)) begin
                        diver1 <= 1;
                        div_clk1 <= ~div_clk1;
                    end
                    else begin
                        diver1 <= diver1 + 1;
                    end
                end
                else if(div_clk1 == 0) begin
                    if ((rsf == 0 && diver1 == (rs2>>1)) || (rsf == 1 && diver1 == (rs2>>1)+1)) begin
                        diver1 <= 1;
                        div_clk1 <= ~div_clk1;
                    end
                    else begin
                        diver1 <= diver1 + 1;
                    end
                end
            end
        end
    end
endmodule